//
//  ShoppingCartDetailViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/6.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//
//  商品详情
import UIKit
import Alamofire
import SwiftyJSON
import SnapKit
import PKHUD
import WebKit

class ShoppingDetailViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, AddCornerUIRectCorner, ShoppingDetailViewDelegate {
    
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var mainTableView: UITableView!
    @IBOutlet weak var subCollectionButton: UIButton!
    private var recommendData: [GoodsModel] = []
    var commodityModel: GoodsModel!
    var headerView:ShoppingDetailView = ShoppingDetailView()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    var page:Int = 0
    var totalPage:Int = 0
    var praiseRate:String=""
    var commentData:[GoodsCommentModel]=[]
    
    var rightBtn: UIButton?
    var datas: [SearchRecommendModel] = []
    var shareImage: UIImageView = UIImageView()
    
    var webView:WKWebView?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.titleLabel(text: "商品详情", nil)
        showRightButtons()
        setUI()
        // Do any additional setup after loading the view.
        if let showImage = commodityModel.coverPath {
    
            shareImage.sd_setImage(with: appendUrl(suffix: showImage), completed: nil)
            
        }
    }
    
//    override func viewWillLayoutSubviews() {
//
//    }
//
    override func shoppingCartTap(_ btn: UIButton) {
        super.shoppingCartTap(btn)
        
        let json = JSON(commodityModel.collected)
        if json.boolValue{
            cancelCollectionProduct(parameter:  ["objId":(commodityModel?.id)!,"objType":"3"], btn: btn)
        }
        else{
            collectionProduct(parameter: ["objId":(commodityModel?.id)!,"objType":"3"],btn:btn)
        }
        
    
    }
    /// 收藏文章
    func collectionProduct(parameter:[String:Any],btn:UIButton) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(collectUrl)"
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameter,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.collectionButton.isSelected = true
                                        self.commodityModel.collected = "\(true)"
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                //                                self.showToast(msg:"请求失败"))
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    /// 取消收藏文章
    func cancelCollectionProduct(parameter:[String:Any],btn:UIButton) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(cancelCollectUrl)"
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameter,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.collectionButton.isSelected = false
                                        self.commodityModel.collected = "\(false)"
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                //                                self.showToast(msg:"请求失败"))
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    @objc override func shareTap() {
        
        let message:UMSocialMessageObject = UMSocialMessageObject()
        let share: UMShareWebpageObject = UMShareWebpageObject.shareObject(withTitle:commodityModel?.label?.name, descr: commodityModel.goodsName, thumImage: shareImage.image)
        share.webpageUrl = appendUrl(suffix: (commodityModel?.shareUrl)!).absoluteString
        message.shareObject = share
        
        ONShareManager.setPreDefinePlatforms([NSNumber(integerLiteral: UMSocialPlatformType.wechatSession.rawValue)
            , NSNumber(integerLiteral: UMSocialPlatformType.QQ.rawValue), NSNumber(integerLiteral: UMSocialPlatformType.sina.rawValue), NSNumber(integerLiteral: UMSocialPlatformType.wechatTimeLine.rawValue)])
        ONShareManager.showShareMenuViewInWindowWithPlatformSelectionBlock { (platformType, info) in
            UMSocialManager.default().share(to: platformType, messageObject: message, currentViewController: self) { (shareResponse, error) in
                
            }
        }
        //        ShareView().showShareView()
    }
    
    func setUI() {
        mainTableView.delegate = self
        mainTableView.dataSource = self
        mainTableView.register(UINib(nibName: "\(ShoppingCommentTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
//        setData()
        if ONCommonManager.checkStringEmpty(origin: commodityModel.id){
                 fetchGoodsDetail(parameters: ["id":commodityModel.id!])
        }
        headerView.delegate = self
        headerView.delegateVc = self
        headerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 211 + 110 + 190 + 10 + 10 + 10)
        headerView.refreshBlock = {
            self.mainTableView.reloadData()
        }
        headerView.selectblock = {
            CommoditySelectionView(items: self.commodityModel).show(leftButtonTaps: { (index) in
                switch index {
                case 0:
                    self.phone()
                case 1:
                    self.goCart()
                default:
                    break
                }
            }) { (model: SpecificationsModel, number, index) in
                switch index {
                case 0:
                    self.goBuyVC(model: model, number: number)
                case 1:
                    self.addCart(model: model, number: number)
                    break
                default:
                    break
                }
            }
        }
        
        mainTableView.tableHeaderView = headerView
        mainTableView.estimatedRowHeight = 100
        mainTableView.rowHeight = UITableViewAutomaticDimension
//        mainTableView.tableFooterView = setBottomView()
        mainTableView.reloadData()
//        bottomView.sizeToFit()
//        let tipView = EmptyTipView(YPoison: bottomView.top + 5)
//        view.addSubview(tipView)
        
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        mainTableView.mj_footer = footer
        mainTableView.mj_footer.isHidden = true
        footerRefresh()
        
    }
    
    func addCart(model: SpecificationsModel, number: Int) -> Void {
        if !MineInfoModel.share.isLogin {
            self.showToast(msg:"您还没有登录")
            let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
            self.navigationController?.pushViewController(loginVC, animated: true)
            return
        }
        if Int(model.inventory!) == 0{
            self.showToast(msg:"库存不足")
            return
        }
        let goodsId :String = model.giId!
        let specId :String = model.id!
        let parameters = ["goodsId":goodsId, "number": number, "specificationId": specId] as [String : Any]
        Alamofire.request(appendUrl(suffix: addCartUrl), method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:"添加购物车成功")
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                        
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"添加失败")
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    
    func showRightButtons() {
        let imageNames = ["right_copy_page"]
        var beforButton: UIButton?
        for (index, imageName) in imageNames.enumerated() {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: imageName), for: .normal)
            button.sizeToFit()
            button.tag = index
            self.view.addSubview(button)
            //            self.view.addSubview(button)
            button.snp.makeConstraints({ (make) in
                make.right.equalTo(self.view.snp.right).offset(-12)
                if beforButton == nil {
                    make.centerY.equalTo(self.view.snp.centerY)
                } else {
                    make.top.equalTo(beforButton!.snp.bottom).offset(30)
                }
                
            })
            button.addTarget(self, action: #selector(rightButtonTap(_ :)), for: .touchUpInside)
            beforButton = button
            self.rightBtn = button
        }
    }
    @objc func rightButtonTap(_ btn: UIButton) {
        
        switch btn.tag {
        case 0:
            let imageSize = UIImage(named: "right_copy_page")
            guard let trueImageSize = imageSize else {return}
            if datas.count > 0{
                RelevantRecommendationsView().showData(datas: datas, rightMargin: trueImageSize.size.width * trueImageSize.scale - 50){(index) in
                    let model:SearchRecommendModel = self.datas[index!]
                    if model.redirectType == "1" {
                        let consultationDetailVC = ConsultationDetailViewController(nibName: "\(ConsultationDetailViewController.self)", bundle: nil, type: .news)
                        consultationDetailVC.title = model.title
                        var mo : ArticleModel = ArticleModel()
                        mo.id = model.id
                        mo.title = model.title
                        mo.coverImgPath = model.image
                        consultationDetailVC.model = mo
                        consultationDetailVC.showRightButtonType = .all
                        self.navigationController?.pushViewController(consultationDetailVC, animated: true)
                    }else {
                        let consultationDetailVC = VideoDetailViewController(nibName: "\(VideoDetailViewController.self)", bundle: nil, type: .video)
                        consultationDetailVC.title = model.title
                        var mo : VideoModel = VideoModel()
                        mo.id = model.id
                        mo.title = model.title
                        mo.coverImgPath = model.image
                        consultationDetailVC.model = mo
                        consultationDetailVC.showRightButtonType = .all
                        self.navigationController?.pushViewController(consultationDetailVC, animated: true)
                    }
                }
            }
            else{
                self.showToast(msg:"没有数据")
            }
        default:
            break
        }
    }
    

    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        self.fetchProductCommentList(parameters: ["page":page,"pageSize":10,"goodId":commodityModel.id!])
    }

    func setData() {
        headerView.setUIAndData(commodiytModel: commodityModel)
        let labelId :String? = self.commodityModel?.label?.id!
        fetchRecommendProductList(parameters:["labelId": labelId!])
        fetchRecommendContentList(parameters:["labelId": labelId!])
        let json = JSON(commodityModel.collected)
        collectionButton.isSelected = json.boolValue
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if commentData.count > 0 {
            return 1
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? ShoppingCommentTableViewCell
        let model = commentData[indexPath.row]
        cell?.showData(model: model)
        return cell!
    }
    func setBottomView() -> UIView {
        let view = UIView()
        view.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 30)
        view.backgroundColor = ONColor.cellBGColor
        let cornerView = UIView()
        cornerView.frame = CGRect(x: 10, y: 0, width: view.width - 20, height: 20)
        cornerView.backgroundColor = UIColor.white
        view.addSubview(cornerView)
        
        self.addCornerWithView(aView: cornerView, aCorners: [.bottomLeft, .bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        return view
    }
    
    // MARK: - someTap
    @IBAction func customerServiceButtonTap(_ sender: UIButton) {
        phone()
    }
    @IBAction func collectionTap(_ sender: UIButton) {
        goCart()
    }
    @IBAction func buyNowTap(_ sender: UIButton) {
        CommoditySelectionView(items: commodityModel).show(leftButtonTaps: { (index) in
            switch index {
            case 0:
                self.phone()
            case 1:
                self.goCart()
            default:
                break
            }
        }) { (model: SpecificationsModel, number, index) in
            switch index {
            case 0:
                self.goBuyVC(model: model, number: number)
            case 1:
                self.addCart(model: model, number: number)
                break
            default:
                break
            }
        }
    }
    @IBAction func addShoppingCartTap(_ sender: UIButton) {
        CommoditySelectionView(items: commodityModel).show(leftButtonTaps: { (index) in
            switch index {
            case 0:
                self.phone()
            case 1:
               self.goCart()
            default:
                break
            }
        }) { (model: SpecificationsModel, number, index) in
            switch index {
            case 0:
                self.goBuyVC(model: model, number: number)
            case 1:
                self.addCart(model: model, number: number)
                break
            default:
                break
            }
        }
    }
    
    func phone() {
        let serviceVC = CustomerServiceViewController(nibName: "\(CustomerServiceViewController.self)", bundle: nil)
        navigationController?.pushViewController(serviceVC, animated: true)
//        let pUrl = URL(string: String(format: "tel:%@", (self.commodityModel?.telephone)!))
//        guard let url = pUrl else { return }
//        if UIApplication.shared.canOpenURL(url) {
//            UIApplication.shared.openURL(url)
//        }
    }
    
    func goCart() {
        let shoppingCartViewController = ShoppingCartViewController(nibName: "\(ShoppingCartViewController.self)", bundle: nil)
        navigationController?.pushViewController(shoppingCartViewController, animated: true)
    }
    
    func goBuyVC(model: SpecificationsModel, number: Int) {
        if !MineInfoModel.share.isLogin {
            self.showToast(msg:"您还没有登录")
            let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
            self.navigationController?.pushViewController(loginVC, animated: true)
            return
        }
        if Int(model.inventory!) == 0{
            self.showToast(msg:"库存不足")
            return
        }
        let buyNowVC = BuyNowViewController(nibName: "\(BuyNowViewController.self)", bundle: nil)
        buyNowVC.tempModel = model
        buyNowVC.number = number
        buyNowVC.type = 2
        self.navigationController?.pushViewController(buyNowVC, animated: true)
    }
    
    // MARK: - ShoppingDetailViewDelegate
    func allCommentTap() {
        if self.totalPage == 0 {
            self.showToast(msg: "暂无评论")
            return
        }
        let allCommentVC = AllCommentViewController(nibName: "\(AllCommentViewController.self)", bundle: nil)
        allCommentVC.commodityModel = self.commodityModel
        allCommentVC.showRightButtonType = .share
        navigationController?.pushViewController(allCommentVC, animated: true)
    }
}

extension ShoppingDetailViewController {
   
    /// 获取商品详情
    func fetchGoodsDetail(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(fetchGoodsDetailUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let dic = json["data"].dictionary!
                                        print("====")
                                        

                                        var model = GoodsModel(fromDic: dic)
                                        if let fileInfo = dic["fileInfos"]{
                                            if let fileInfos = fileInfo.array {
                                                model.initFileInfos(arr: fileInfos)
                                            }
                                        }
                                        
                                        if let specification = dic["specifications"]{
                                            let specifications = specification.array!
                                            model.initSpecifications(arr: specifications)
                                        }
                                        
                                        
                                        
                                        let label = dic["label"]
                                        if !(label?.isEmpty)!{
                                            model.initLabel(dic: (label?.dictionary!)!)
                                        }

                                        self.commodityModel = model
                                        self.setData()
                                    }
                                    else{

                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    /// 获取推荐商品列表数据
    func fetchRecommendProductList(parameters:[String:String]) -> Void {
        let requesturl = "\(BaseURL)\(recommendShoppingListUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: nil,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"]["rows"].array!
                                        self.recommendData.removeAll()
                                        
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            
                                            var model = GoodsModel(fromDic: dic)
                                            model.type = "4"
                                            self.recommendData.append(model)
                                        }
                                        
                                        self.headerView.updateCollectionViewData(recommend: self.recommendData)
                                        
                                    }
                                    else{

                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    
    /// 获取推荐文章列表数据
    func fetchRecommendContentList(parameters:[String:String]) -> Void {
        let requesturl = "\(BaseURL)\(recommendContentListUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"].array!
                                        self.datas.removeAll()
                                        
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            
                                            let model = SearchRecommendModel(fromDic: dic)
                                            
                                            self.datas.append(model)
                                            
                                        }
                                        if self.datas.count == 0{
                                            self.rightBtn?.isHidden = true
                                        }
                                    }
                                    else{
                                        
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }

    /// 获取商品列表评论数据
    func fetchProductCommentList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(goodsCommentListUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"]["rows"].array!
                                        self.totalPage = json["data"]["total"].int!
                                        self.praiseRate = json["data"]["praiseRate"].string!
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            
                                            var model = GoodsCommentModel(fromDic: dic)
                                            if let pic = dic["pics"]{
                                                let pics = pic.array!
                                                
                                                model.initPics(arr: pics)
                                            }
                                            
                                            let author = dic["commentUser"]
                                            if !(author?.isEmpty)!{
                                                model.initAuthor(dic: (author?.dictionary!)!)
                                            }
                                            self.commentData.append(model)
                                        }
                                        if self.totalPage == self.commentData.count{
                                            self.mainTableView.mj_footer.isHidden = true
                                        }
                                        else{
                                            self.mainTableView.mj_footer.isHidden = false
                                        }
                                        print(self.commentData)
                                        self.mainTableView.reloadData()
                                        self.headerView.updateCommentHeader(count: String(self.totalPage), rate: self.praiseRate)
                                    }
                                    else{
                                        
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
}
